package io.github.jsp.service.impl;

import io.github.jsp.dao.JobInfoMapper;
import io.github.jsp.model.JobInfo;
import io.github.jsp.service.JobInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class JobInfoServiceImpl implements JobInfoService {
    
    @Autowired
    private JobInfoMapper jobInfoMapper;
    
    @Override
    public JobInfo getById(Integer id) {
        return jobInfoMapper.selectById(id);
    }
    
    @Override
    public List<JobInfo> getAll() {
        return jobInfoMapper.selectAll();
    }
    
    @Override
    public List<JobInfo> getByStatus(Integer status) {
        return jobInfoMapper.selectByStatus(status);
    }
    
    @Override
    public List<JobInfo> getByTriggerStatus(Integer triggerStatus) {
        return jobInfoMapper.selectByTriggerStatus(triggerStatus);
    }
    
    @Override
    public List<JobInfo> getByGroup(String jobGroup) {
        return jobInfoMapper.selectByGroup(jobGroup);
    }
    
    @Override
    public Integer save(JobInfo jobInfo) {
        if (jobInfo.getId() == null) {
            jobInfoMapper.insert(jobInfo);
            return jobInfo.getId();
        } else {
            jobInfoMapper.update(jobInfo);
            return jobInfo.getId();
        }
    }
    
    @Override
    public int update(JobInfo jobInfo) {
        return jobInfoMapper.update(jobInfo);
    }
    
    @Override
    public int updateTriggerTime(Integer id, Long triggerTime) {
        return jobInfoMapper.updateTriggerTime(id, triggerTime, null);
    }
    
    @Override
    public int updateTriggerStatus(Integer id, Integer triggerStatus) {
        return jobInfoMapper.updateTriggerStatus(id, triggerStatus);
    }
    
    @Override
    public int deleteById(Integer id) {
        return jobInfoMapper.deleteById(id);
    }
    
    @Override
    public List<JobInfo> getSchedulableJobs() {
        List<JobInfo> allJobs = jobInfoMapper.selectAll();
        return allJobs.stream()
                .filter(job -> job.getJobStatus() == 1 && job.getTriggerStatus() == 1)
                .collect(Collectors.toList());
    }
}